<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <div class="b_common_title">基本信息</div>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户名" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:15px">
               <!-- <a-input v-if="!zhen" @click="jia" :maxLength='11' placeholder="请输入用户名"></a-input> -->
               <a-input v-decorator="['username', validatorRules.username]" :maxLength='10' placeholder="请输入用户名"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:15px">
              <a-input v-decorator="['phone', validatorRules.phone]" :maxLength='11' placeholder="请输入手机号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="seePassword">
            <a-form-item label="密码" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:15px">
              <a-input-password autocomplete="new-password" v-decorator="['password', validatorRules.password]" :maxLength='20' placeholder="请输入密码"></a-input-password>
            </a-form-item>
          </a-col>
          <a-col :span="12">
             <a-form-item label="所属单位" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:15px">
               <a-select
                v-decorator="['relTenantIds', { rules: [{ required: true, message: '请选择所属单位' }] }]"
                :disabled="editdisabled"
                placeholder="请选择所属单位"
                :trigger-change="true"
              >
                <a-select-option v-for="item in positionList" :key="item.id" :value="item.tenantId">
                  {{ item.principalName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="职位" :labelCol="labelCol" :wrapperCol="wrapperCol"  :colon="false" style="margin-bottom:15px">
               <a-input v-decorator="['post', validatorRules.post]" :maxLength='10' placeholder="请输入职位"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <div class="b_common_title">权限</div>
          </a-col>
        </a-row>
        <a-row>
         <a-form-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol"  :colon="false" style="margin-bottom:15px">
            <a-checkbox-group @change="onChange" v-decorator="['systemIds', validatorRules.systemIds]">
                <template v-for="(item, key) in tqppSystemList" >
                  <a-col :span="24" :key="item.id">
                    <a-checkbox :key="key" :value="item.id" :disabled="chooseSystems(item)">{{  item.name }}
                      <template v-if="item.code==='szdp'">
                        (<a-radio-group v-decorator="['specification',{initialValue:1},validatorRules.specification]">
                          <a-radio :value="1">1920*1080</a-radio>
                          <a-radio :value="2">6.72m*1.92m</a-radio>
                        </a-radio-group>)
                      </template>
                    </a-checkbox>
                  </a-col>
                </template>
            </a-checkbox-group>
          </a-form-item>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JMultiSelectTag from "@/components/dict/JMultiSelectTag"
  import { duplicateCheck } from '@/api/api'
   import { mapGetters } from 'vuex'
  export default {
    name: 'TxppServiceItemsForm',
    components: {
      JFormContainer,
      JDictSelectTag,
      JMultiSelectTag,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        userName:'',
        result:{},
        userId:'',
        seePassword:true,
        positionList:[],
        tqppSystemList:[],//权限列表
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           phone:{
             rules:[
               { validator:this.validatePhone},
               { required: true, message: '请输入手机号!'},
             ]
           },
           password:{
             rules:[
               { validator:this.validatePassword},
               { required: true, message: '请输入密码!'},
             ]
           },
          username: {
            rules: [
              { validator:this.validateUsername},
              { required: true, message: '请输入用户名!'},
            ]
          },
          post: {
            rules: [
              { validator:this.validatepost},
            ]
          },
        },
        url: {
          add: "/sys/user/save",
          edit: "/sys/user/modify",
          queryById: "/sys/user"
        }
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    watch:{
      tqppSystemList:{
        immediate:true,
         handler(val) {
            if(this.userInfo().username==='admin'){
            const arr = []
            arr.push(...(val.filter(i=>i.name=== "经纪人监管系统"||i.name=== "数字大屏"||i.name=== "大屏数据维护")))
            const ids =[]
            arr.map(k=>
              ids.push(k.id)
            )
            this.$nextTick(()=>{
              setTimeout(() => {
                 this.form.setFieldsValue({'systemIds':ids})
              })
            })
            }
          }
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    mounted () {
        this.getTxppSubjectList()
        this.getTqppSystemList()
    },
    methods: {
      ...mapGetters(['userInfo']),
      chooseSystems(item){
        if(this.seePassword){
          if(item.code==="gszyglxt"||item.code==="sznc"){
            return true
          }else{
            return false
          }
        }else{
          if(!this.result.user.thirdType){
            if(item.code==="gszyglxt"||item.code==="sznc"){
              return true
            }else{
              return false
            }
          }else{
            if(item.code==="jjrjgxt"||item.code==="szdp"||item.code==="dpsjwh"){
              return true
            }else{
              return false
            }
          }
        }
      },
      validateUsername(rule, value, callback) {
         if (!value) {
        callback()
      } else {
         if (new RegExp(/^([\u4E00-\u9FA5|a-zA-Z])+$/).test(value)) {
           var params = {
            tableName: 'sys_user',
            fieldName: 'username',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('用户名已存在!')
            }
          })
        }else{
           callback("仅可输入中文、英文大小写!");
        }
      }
     
    },
     validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('手机号已存在!')
            }
          })
        } else {
          callback('请输入正确格式的手机号码!')
        }
      }
    },
      validatePassword(rule,value,callback){
        if (!value || new RegExp(/[0-9a-zA-Z]{6,20}/).test(value)){
          callback();
        }else{
          callback("仅可输入英文大小写、数字");
        }
      },
    
      validatepost(rule,value,callback){
        if (!value || new RegExp(/[\u4e00-\u9fa5]/).test(value)){
          callback();
        }else{
          callback("仅可输入中文");
        }
      },
      validateSpecification(rule,value,callback){
        if (this.form.getFieldValue('username')){
          callback();
        }else{
          callback("仅可输入中文");
        }
      },
      async getTxppSubjectList() {
        // 获取单位
        try {
          const res = await getAction('/loquat/txppSubject/allList')
          if (res.success) {
            this.positionList = res.result
          }
        } catch (error) {
          console.log(error)
        }
      },
       async getTqppSystemList() {
        // 获取权限列表
        try {
          const res = await getAction('/loquat/tqppSystem/list')
          if (res.success) {
            this.tqppSystemList = res.result
          }
        } catch (error) {
          console.log(error)
        }
      },
       async getDetails(id) {
        // 获取权限列表
        try {
          const res = await getAction(`/sys/user/user/${id}`)
          if (res.success) {
            this.result = res.result
          }
        } catch (error) {
          console.log(error)
        }
      },
      add() {
        this.edit({},true)
      },
      edit(record,show) {
        this.form.resetFields()
        if(!show){
          this.getDetails(record.id).then(()=>{
          let obj = this.result.user
          obj.relTenantIds = Number(obj.relTenantIds)
          obj.systemIds = this.result.systemIds.split(',')
          obj.specification = this.result.specification
            this.model = Object.assign({}, obj)
            this.visible = true
            this.seePassword = show
            this.userId = obj.id
            this.$nextTick(() => {
              setTimeout(() => {
                this.form.setFieldsValue(pick(this.model, 
                'username',
                'phone',
                'password',
                'systemIds',
                'relTenantIds',
                'post',
                'specification'))
            })
          });
        })
        }else{
            this.model = Object.assign({}, record)
            this.visible = true
            this.seePassword = show
            this.userId = record.id
            this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model, 
              'username',
              'phone',
              'password',
              'systemIds',
              'relTenantIds',
              'post',
              'specification'))
          })
        }
    },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.id};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit(res.result,false);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          console.log(this.form.getFieldValue('systemIds'));
          if(!this.form.getFieldValue('systemIds')||this.form.getFieldValue('systemIds').length<1||this.form.getFieldValue('systemIds')[0]===''){
            this.$message.warning('请至少选择一条权限')
            return
          }else{
             if(values.systemIds){
              values.systemIds = values.systemIds.join(',')
              }
              if (!err) {
                that.confirmLoading = true;
                let httpurl = '';
                let method = '';
                if(!this.model.id){
                  httpurl+=this.url.add;
                  method = 'post';
                }else{
                  httpurl+=this.url.edit;
                  method = 'put';
                }
                let formData = Object.assign(this.model, values);
                console.log("表单提交数据",formData)
                httpAction(httpurl,formData,method).then((res)=>{
                  if(res.success){
                    that.$message.success(res.message);
                    that.$emit('ok');
                  }else{
                    that.$message.warning(res.message);
                  }
                }).finally(() => {
                  that.confirmLoading = false;
                })
              }else{
           }
          }
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,
          'username',
          'phone',
          'password',
          'systemIds',
          'relTenantIds',
          'post',
          'specification'
        ))
      },
    }
  }
</script>
<style lang="less">
.ant-checkbox-wrapper{
margin: 10px 0;
}
.ant-radio-group{
padding: 0 10px;
}
.ant-form-item-control{
  line-height: 0px!important
}
.ant-col-sm-5{
  width: 100px;
}
.projectstyle{
.ant-col-sm-16{
  width: 88%;
  .ant-form-item-control{
    .ant-form-item-children{
      >div{
        width: 95% !important;
      }
    }
  }
}
}

</style>